/*
* You could easily make this into a reusable control if you wanted, but in this case it's written from scratch
*/
var GridController = function(pageSize) {
    if(pageSize)
        this._pageSize = pageSize;
}

GridController.prototype = {
    _pageSize : 10,
    
    Sort : function(property, defaultDescending) {
        if(this.model.GridState.SortProperty == property) 
            // Reverse the sort order
            this.model.GridState.SortDescending = !this.model.GridState.SortDescending;
        else {
            // Assign the new sort property
            this.model.GridState.SortProperty = property;
            this.model.GridState.SortDescending = defaultDescending;
        }
        this.model.GridState.PageIndex = 0;
    },

    GetSortedData : function() {
        // Get independent copy of data
        var data = this.model.Records.slice(); 
        
        // Sort the copy
        if(this.model.GridState.SortProperty) {
            var ordering = this.model.GridState.SortDescending ? -1 : 1;
            var self = this;
            // Use the Javascript "sort" feature that lets us pass a delegate to define the ordering of any two elements
            // We can dynamically pick out the relevant sort property using the "eval" function
            data.sort(function(left, right) { 
                return (ordering*self._compare(eval("left."+self.model.GridState.SortProperty), eval("right."+self.model.GridState.SortProperty))) || self._compare(left.ID, right.ID);
            });
        }
        
        // Then pick out the appropriate page
        return data.slice(this.model.GridState.PageIndex*this._pageSize, (this.model.GridState.PageIndex+1)*this._pageSize);
    },  
    
    GetPageCount : function() {
        return Math.ceil(this.model.Records.length / this._pageSize);
    },
    
    ShowPage : function(i) {
        this.model.GridState.PageIndex = i;
    },
    
    SelectRecord : function(recordID) {
        this.model.GridState.SelectedRecordID = recordID;
    },
    
    _compare : function(left, right) {
        // Trivially orders elements in their native ordering
        if(left < right)
            return -1;
        if(right < left)
            return 1;
        return 0;
    } 
}